<template>
  <div class="menu" v-loading="loading" style="height:calc(80vh - 100px);">
    <p style="padding:10px">
      当前角色:<font color="red">{{ roleName }}</font>
    </p>
    <el-scrollbar class="el-scrollbar-vertical user-scrollbar">
      <el-tree
        :data="menuTree"
        show-checkbox
        node-key="id"
        default-expand-all
        :props="menuTreeProp"
        :default-checked-keys="menuTreeCheck"
        @check="onHandleMenuTreeCheck"
      ></el-tree>
    </el-scrollbar>
    <el-row>
      <el-col>
        <el-button size="small" @click="onCloseMenuDialog">取消</el-button>
        <el-button type="primary" size="small" @click="onSubmitMenuInfo"
          >提交</el-button
        >
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { roleManage, menuManage } from '@/api'

export default {
  name: 'form-menu',
  componentName: 'formMenu',
  data() {
    return {
      loading: false,
      menuTree: null,
      menuTreeProp: {
        children: 'children',
        label: 'menuName'
      },
      treeCheck: [],
      menuTreeCheck: []
    }
  },
  props: {
    roleId: String,
    roleName: String
  },
  watch: {
    roleId(newV, oldV) {
      if (newV) {
        this.getMenuTree()
      }
    }
  },
  created() {
    this.getMenuTree()
  },
  methods: {
    async getMenuTree() {
      try {
        const menu = await menuManage.treeByRoleId(this.roleId)
        console.log(menu)
        var menuTreeCheck = []
        menu.data.map(d => {
          if (d.checked === '1') {
            menuTreeCheck.push(d.id)
          }
          d.children.forEach(c => {
            if (c.checked === '1') {
              menuTreeCheck.push(c.id)
            }
            c.children.forEach(b => {
              if (b.checked === '1') {
                menuTreeCheck.push(b.id)
              }
            })
          })
        })
        this.menuTreeCheck = menuTreeCheck
        this.menuTree = menu.data
      } catch {
        this.$message.error({
          message: '获取菜单失败...'
        })
      }
    },
    onHandleMenuTreeCheck(item, menu) {
      this.treeCheck = menu.checkedKeys.concat(menu.halfCheckedKeys)
    },
    onCloseMenuDialog() {
      this.$emit('onSubmit', false)
    },
    async onSubmitMenuInfo() {
      this.loading = true
      try {
        const menu = await roleManage.setRolePermission({
          roleId: this.roleId,
          permissionId: this.treeCheck.join(',')
        })
        this.loading = false
        this.$message.success({
          message: '成功了'
        })
        this.$emit('onSubmit', true)
      } catch {
        this.loading = false
        this.$message.error({
          message: '失败了'
        })
        this.$emit('onSubmit', false)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.el-scrollbar-vertical {
  height: calc(100% - 50px);
  box-sizing: border-box;
  & /deep/ .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}
</style>
